#ifndef LUA_STATE_MANAGER_H_
#define LUA_STATE_MANAGER_H_

#include "LuaManager.h"

template <class T>
class Lua_State_Manager
{
public:
    void SetUp(T* owner, LuaPlus::LuaObject table, const char* luaObj)
    {
        m_owner = LuaManager::Instance()->GetOwner()->BoxPointer(owner);
        m_owner.SetMetaTable(table);
        m_currentState = LuaManager::Instance()->GetOwner()->GetGlobal(luaObj);
        if(m_currentState.IsTable())
        {
            //call on enter on the new state
            if(m_currentState["OnEnter"].IsFunction())
            {
                LuaPlus::LuaFunction<void> OnEnter = m_currentState["OnEnter"];
                OnEnter(m_owner);
            }
        }
    }
    void ChangeState(const char* newState)
    {
        LuaPlus::LuaObject ns = LuaManager::Instance()->GetOwner()->GetGlobal(newState);
        ChangeState(ns);
    }
    void ChangeState(LuaPlus::LuaObject newState)
    {
        if(!newState.IsTable())
            return;

        //clean up the old state
        if(m_currentState.IsTable())
        {
            if(m_currentState["OnExit"].IsFunction())
            {
                LuaPlus::LuaFunction<void> OnExit = m_currentState["OnExit"];
                OnExit(m_owner);
            }
        }
        //call on enter on the new state
        if(newState["OnEnter"].IsFunction())
        {
            LuaPlus::LuaFunction<void> OnEnter = newState["OnEnter"];
            OnEnter(m_owner);
        }
        m_currentState = newState;
    }
    void Update() 
    {
        if(m_currentState.IsTable())
            if(m_currentState["OnUpdate"].IsFunction())
            {
                LuaPlus::LuaFunction<void> OnUpdate = m_currentState["OnUpdate"];
                OnUpdate(m_owner);
            }
    }
    LuaPlus::LuaObject GetCurrentState()  {return m_currentState;}

private:
    LuaPlus::LuaObject m_owner;
    LuaPlus::LuaObject m_currentState;
};

#endif